package com.skyworth.web.order.controller;

import com.skyworth.utils.CookieUtil;
import com.skyworth.utils.StrUtil;
import com.skyworth.web.common.ApiResponse;
import com.skyworth.web.common.controller.BaseController;
import com.skyworth.web.order.domain.OrderModel;
import com.skyworth.web.order.form.OrderForm;
import com.skyworth.web.order.service.OrderService;
import com.skyworth.web.ordermenu.OrderMenuService;
import com.skyworth.web.admin.table.service.ITableService;
import com.skyworth.web.common.form.MenuCss;
import com.skyworth.web.wechat.common.AppSecretInfo;
import com.skyworth.web.wechat.engin.ServerEngin;
import com.skyworth.web.wechat.entity.AccessTokenModel;
import com.skyworth.web.wechat.protocol.NotifyMsg;
import com.skyworth.web.wechat.service.AccessTokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by skyworth on 2016/6/23.
 */

@Controller
public class OrderController extends BaseController {
    Logger LOG = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private OrderMenuService orderMenuService;

    @Autowired
    private MenuCss menuCss;

    @Autowired
    private ITableService iTableService;

    //REST api begin

    /**
     * 服务员拒绝订单接口
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value={"/api/setorder/refuse/{id}"},method = RequestMethod.GET)
    public Object refuseOrder(@PathVariable Long id){

        ApiResponse apiResponse = new ApiResponse();
        orderService.refuseOrder(id);

        apiResponse.setSuccess(true);
        apiResponse.setMessage("success");

        Map<String,Object> data = new HashMap<>();
        data.put("orderId",id);

        apiResponse.setData(data);
        return apiResponse;
    }

    /**
     * 服务员确认某个订单
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value={"/api/setorder/accept/{id}"},method = RequestMethod.GET)
    public Object acceptOrder(@PathVariable  Long id){
        ApiResponse apiResponse = new ApiResponse();
        orderService.acceptOrder(id);
        apiResponse.setSuccess(true);

        Map<String,Object> data = new HashMap<>();
        data.put("orderId",id);

        apiResponse.setData(data);
        return apiResponse;
    }




    @ResponseBody
    @RequestMapping(value={"/api/getorders/store/{sId}/user/{uId}/{page}"},method = RequestMethod.GET)
    public Map<String,Object> getOrderList(@PathVariable("sId") Long sId,@PathVariable String uId,@PathVariable Integer page){
        Map<String,Object> result = orderService.getOrderForUser(sId,uId,page);
        return result;
    }

    @ResponseBody
    @RequestMapping(value={"/api/getorders/user/{id}/{page}"})
    public Page<OrderModel> getAllByUserId(@PathVariable("id") String id, @PathVariable("page") int page){
        return orderService.queryByUserId(id,page,50);
    }
    /**
     * 获取订单详情
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = {"/api/getorder/table/{id}"}, method = RequestMethod.GET)
    public OrderModel queryDetailByTableId(@PathVariable("id") long id) {
        return orderService.getLastByTableId(id);
    }

    /**
     * 获取订单详情
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = {"/api/getorder/user/{userId}"}, method = RequestMethod.GET)
    public OrderModel queryDetailByUserId(@PathVariable String userId, HttpServletRequest request) {
        String storeId = CookieUtil.getCookie("storeId",request);
        OrderModel orderModel = null;
        try{
            int sId = Integer.parseInt(storeId);
            orderModel = orderService.getLastOrder(sId,userId);
        }catch (NumberFormatException e){
            e.printStackTrace();
        }
        return orderModel;
    }
    /**
     * 获取订单详情
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = {"/api/getorder/order/{id}"}, method = RequestMethod.GET)
    public OrderModel queryByOrderId(@PathVariable("id") long id) {

        return orderService.query(id);
    }

    @ResponseBody
    @RequestMapping(value = {"/api/order/delete/{id}"}, method = RequestMethod.GET)
    public Map<String,String> removeByOrderId(@PathVariable("id") long id) {
         Map<String,String> result = new HashMap<>();
        try {
            orderService.removeById(id);
            result.put("status","success");
        }catch (Exception e){
            result.put("status","error");
        }
        return result;
    }

    /**
     * 添加一个订单
     * @param orderForm
     * @param model
     * @return
     */
    @RequestMapping(value = {"/api/order/"}, method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> create(HttpServletResponse response,@ModelAttribute OrderForm orderForm, Model model) {
        Map<String,Object> result = new HashMap<>();
        System.out.println(orderForm);
        System.out.println("tableId:"+orderForm.getTableId()+",state:"+orderForm.getState());
        if(orderForm==null){
            result.put("status","error");
            return result;
        }
        if(orderForm!=null && orderForm.getTableId()>0){
            OrderModel om = orderService.getLastByTableId(orderForm.getTableId());
            if(om!=null && om.id>0){
                result.put("status","repeat");
                return result;
            }

        }

        OrderModel orderModel = OrderForm.toOrderModel(orderForm);
        orderModel = orderService.saveOrUpdate(orderModel,orderForm.getFoods());

        if(orderModel!=null && orderModel.state!=OrderService.ORDER_CART) {
            final String openid = orderModel.userId;
            final String orderId = StrUtil.objectToString(orderModel.id);
            new Thread() {
                public void run() {

                    AccessTokenModel atm = accessTokenService.findByAppId(AppSecretInfo.appId);
                    String accessToken = atm.getAccessToken();
                    Map<Object, Object> handleMap = NotifyMsg.orderHandleMsg(openid, orderId);
                    ServerEngin.getInstance().sendTemplateMsg(accessToken, handleMap);
                }
            }.start();


            CookieUtil.setCookie("unpayed", String.valueOf(orderModel.id), response);

            OrderModel toClientModel = orderService.query(orderModel.id);

            result.put("detail", toClientModel);
        }
        result.put("status","success");

        return result;
    }
}